<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebRTC Live Streaming</title>
</head>

<body>
    <h1>WebRTC Live Streaming</h1>
    <video id="localVideo" autoplay playsinline></video>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        const localVideo = document.getElementById('localVideo');
        const socket = io();

        let localStream;
        let peerConnection;

        async function start() {
            localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
            localVideo.srcObject = localStream;

            const janus = new Janus({
                server: 'http://localhost:8088/janus',
                success: () => {
                    janus.attach({
                        plugin: 'janus.plugin.videoroom',
                        success: (pluginHandle) => {
                            peerConnection = new RTCPeerConnection({
                                iceServers: [
                                    { urls: 'stun:stun.l.google.com:19302' }
                                ]
                            });

                            localStream.getTracks().forEach(track => {
                                peerConnection.addTrack(track, localStream);
                            });

                            peerConnection.onicecandidate = event => {
                                if (event.candidate) {
                                    pluginHandle.send({ message: { request: 'trickle', candidate: event.candidate } });
                                }
                            };

                            const offer = await peerConnection.createOffer();
                            await peerConnection.setLocalDescription(offer);

                            pluginHandle.send({
                                message: {
                                    request: 'join',
                                    room: 1234,
                                    ptype: 'publisher',
                                    display: 'publisher'
                                },
                                jsep: offer
                            });
                        },
                        onmessage: (msg, jsep) => {
                            if (jsep) {
                                peerConnection.setRemoteDescription(new RTCSessionDescription(jsep));
                            }
                        }
                    });
                }
            });
        }

        start();
    </script>
</body>

</html>